package com.yunupmall.service.ford.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.BeanUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunupmall.api.fordVO.ReturngoodsVO;
import com.yunupmall.api.fordentity.ExpandOrder;
import com.yunupmall.api.fordentity.Order;
import com.yunupmall.api.fordentity.Returngoods;
import com.yunupmall.api.fordentity.SpecsCommodity;
import com.yunupmall.entity.admin.memberpojo.Member;
import com.yunupmall.mapper.FordMapper.ReternGoodMapper;
import com.yunupmall.service.admin.service.SpecsCommdityService;
import com.yunupmall.service.ford.service.ExpandOrderService;
import com.yunupmall.service.ford.service.OrderService;
import com.yunupmall.service.ford.service.ReternGoodService;
import com.yunupmall.uits.SessionUtis;
import lombok.AllArgsConstructor;
import net.sf.jsqlparser.expression.operators.relational.Between;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

@Service
@AllArgsConstructor
public class ReturnGoodimpl extends ServiceImpl<ReternGoodMapper, Returngoods>  implements ReternGoodService {
    private final OrderService orderService;
    private final ExpandOrderService expandOrderService;
    private final SpecsCommdityService specsCommdityService;


    private final String APP_ID = "2021000119644933";
    private final String APP_PRIVATE_KEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDJSouxFgBpNgoaR5DwbJmA1Y3KjOQg0vguUimgHRqQwviqkWcrX4Hqad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rl75C12p1RYKwrsriaGhBgEFGoPisACUxlMug0XR8OlUreq0Kgl6JO/WQ34JVN4klkm7/LuZzEUWTECgYAF8M04vCj0NAvGYt91QL7XFL9dqcpEJL9Az8kjnN718KfwYGI7p0/2Ljt8d5znRM9ZOTk8nny3ZHSXVVZzM01vfij/nJyyZFqP2zDNUZCqUVpzVL8B8oNm5EAJWjx4To91fT4xJXKYQN2w/qZXw/vzp/jJV7YRLY5MUCqngoGU7QKBgD7IbsATbsqix/JEWGbSZ/8DzD/PsS0ePk8M4YBbqJgD9X6K2jGeHDt97vu1aTk4FCgjA1JADl0vzRirLvwJvYvd1lFilc3W8JAdV3yXNlkqFaAD2HyPRberL4fNgyiCIvqmliXSQK/zWE2na+p35D51dw+KuTzsy1k+48L6iyd5";
    private final String CHARSET = "UTF-8";
    private final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAg//3meVzoOeC5E/M1TTwtyC+IV62DprhqAy6UC9VKlqNJlcdnfN2Y01QBanDaCFmN8IFA2cy5mff/X86tH4GQ58ful/e1MhBM2jkSdjdgQ5060ksI3A8/r3Ic/cl77Dow7+J51uSXMI9mr1xbZVDyUMsHtdbAH9Eue31osPzrOaPxljg8jk02SfA6xiSSpyWytvgXZLLNnp1brPC0/tAwxAz9nkBGyWfhu/vEqkmNAIf/9mVfJGnvmJnXxSTI4aaJGkRslJD7g4RfRXtXACkuRUWptIFFtHo7hTAIZuohPyynK7oMuv3hK0pt18Y0AnI3xEv94qwilrZVd+9lqfevwIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL ="https://openapi.alipaydev.com/gateway.do";
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    private final String NOTIFY_URL = "http://50p71z4960.qicp.vip/order/returnOrderData";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    private final String RETURN_URL = "http://192.168.0.104:8888/skippage?url=udai_order";

    @Override
    @Transactional
    public String saveData(Integer refund, Integer cargoStatus, String reason, String remarks,Integer orderId) {
        Order order = new Order();
        order.setId(orderId);
        order.setOrderStatic(5);
        orderService.updateById(order);
        Returngoods returngoods = new Returngoods();
        if (ObjectUtils.isNotEmpty(refund)){
            returngoods.setRefundId(refund);
            switch (refund) {
                case 0:
                    returngoods.setRefund("仅退款");
                    break;
                case 1 :
                    returngoods.setRefund("退货退款");
                    break;
            }
        }
        if (ObjectUtils.isNotEmpty(cargoStatus)){
            returngoods.setCargoStatusId(cargoStatus);
            switch (cargoStatus) {
                case 0:
                    returngoods.setCargoStatus("未收到货");
                    break;
                case 1 :
                    returngoods.setCargoStatus("已收到货");
                    break;
            }

        }
        if (ObjectUtils.isNotEmpty(reason)) {
            returngoods.setReason(reason);
        }
        if (ObjectUtils.isNotEmpty(remarks)) {
            returngoods.setRemarks(remarks);
        }
        Order byId = orderService.getById(orderId);
        returngoods.setOrderId(byId.getId());
        returngoods.setAmount(byId.getPrice());
        returngoods.setOrderUuid(byId.getOrderUuid());
        returngoods.setCeaterTime(LocalDateTime.now());
        returngoods.setDeflag(0);
        returngoods.setStatics(1);
        returngoods.setMId(byId.getMId());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String newDate = sdf.format(new Date());
        String result = "";
        Random random = new Random();
        for (int i = 0; i < 5; i++) {
            result += random.nextInt(10);
        }
        returngoods.setNumber(newDate + result);
        this.save(returngoods);
        return "成功";
    }

    /**
     * 分页
     * @param returngoodsVO
     * @return
     */
    @Override
    public  Page<ReturngoodsVO> pageData(ReturngoodsVO returngoodsVO) {
        LambdaQueryWrapper<Returngoods> wrapper = new LambdaQueryWrapper<>();
        if (ObjectUtil.isNotEmpty(returngoodsVO.getFlag())){
            Member member = (Member) SessionUtis.getSessionAttribute("member");
            if (ObjectUtil.isNotEmpty(member)){
                wrapper.eq(Returngoods::getMId,member.getId());
            }else {
                throw new RuntimeException("没有用户信息");
            }
        }
        if (ObjectUtil.isNotEmpty(returngoodsVO.getOrderUuid())){
            wrapper.eq(Returngoods ::getOrderUuid,returngoodsVO.getOrderUuid());
        }
        if (ObjectUtil.isNotEmpty(returngoodsVO.getNumber())){
            wrapper.eq(Returngoods ::getNumber,returngoodsVO.getNumber());
        }
        wrapper.eq(Returngoods::getDeflag,0).orderByDesc(Returngoods::getCeaterTime);
        Page<Returngoods> returngoodsPage = new Page<>(returngoodsVO.getPage(), returngoodsVO.getLimit());
        Page<Returngoods> repage = this.page(returngoodsPage, wrapper);
        List<ReturngoodsVO> returngoodsVOList = new ArrayList<>();
        repage.getRecords().forEach(returngoods -> {
            ReturngoodsVO returngoodsVO1 = new ReturngoodsVO();
            BeanUtil.copyProperties(returngoods, returngoodsVO1);
            if (ObjectUtil.isNotEmpty(returngoods.getStatics())){
                switch (returngoods.getStatics()){
                    case 1:
                        returngoodsVO1.setStaticsString("买家申请售后");
                        break;
                    case 2 :
                        returngoodsVO1.setStaticsString("卖家审核通过");
                        break;
                    case 3 :
                        returngoodsVO1.setStaticsString("卖家审核不通过");
                        break;
                    case 4 :
                        returngoodsVO1.setStaticsString("买家已操作退回");
                        break;
                    case 5 :
                        returngoodsVO1.setStaticsString("完成");
                        break;
                }
            }
            returngoodsVOList.add(returngoodsVO1);
        });
        Page<ReturngoodsVO> returngoodsVOPage = new Page<>();
        returngoodsVOPage.setRecords(returngoodsVOList);
        returngoodsVOPage.setTotal(repage.getTotal());
        returngoodsVOPage.setSize(repage.getSize());
        returngoodsVOPage.setCurrent(repage.getCurrent());
        return returngoodsVOPage;
    }

    //修改
    @Override
    @Transactional
    public String updateData(ReturngoodsVO returngoodsVO) {
        if (ObjectUtil.isEmpty(returngoodsVO.getId())){
            throw new RuntimeException("id为空");
        }
        Order order = new Order();
        switch (returngoodsVO.getStatics()){
            case 2:
                order.setId(returngoodsVO.getOrderId());
                order.setOrderStatic(6);
                break;
            case 3:
                order.setId(returngoodsVO.getOrderId());
                order.setOrderStatic(7);
                break;
            case 4:
                order.setId(returngoodsVO.getOrderId());
                order.setOrderStatic(8);
                break;
            case 5 :
                order.setId(returngoodsVO.getOrderId());
                order.setOrderStatic(9);
                break;
        }
        if (!orderService.updateById(order)){
            throw new RuntimeException("订单更新失败");
        }
        Returngoods returngoods = new Returngoods();
        BeanUtil.copyProperties(returngoodsVO,returngoods);
        if (this.updateById(returngoods)) {
            return "成功";
        }else {
            throw new RuntimeException("修改失败");
        }
    }

    @Override
    @Transactional
    public String complete(ReturngoodsVO returngoodsVO) {
        try {
        this.updateData(returngoodsVO);
        //库存回填
            Integer orderId = returngoodsVO.getOrderId();
            LambdaQueryWrapper<ExpandOrder> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ExpandOrder::getOrderId,orderId);
            wrapper.eq(ExpandOrder::getDeflag,0);
            List<ExpandOrder> list = expandOrderService.list(wrapper);
            list.forEach(expandOrder -> {
                SpecsCommodity byid = specsCommdityService.byid(expandOrder.getSpecsId());
                SpecsCommodity specsCommodity = new SpecsCommodity();
                specsCommodity.setId(byid.getId());
                specsCommodity.setStocks((byid.getStocks()+expandOrder.getCount()));
                if (!specsCommdityService.updateById(specsCommodity)) {
                    throw new RuntimeException("库存更新失败");
                }
            });
            Returngoods byId = this.getById(returngoodsVO.getId());
            AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
            AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();
            JSONObject bizContent = new JSONObject();
            bizContent.put("out_trade_no",byId.getOrderUuid());
            bizContent.put("refund_amount",byId.getAmount());
            bizContent.put("refund_reason",byId.getReason());
            alipayRequest.setBizContent(bizContent.toString());
            String result = alipayClient.execute(alipayRequest).getBody();
            JSONObject jsonObject = JSON.parseObject(result);
            String alipay_trade_refund_response = jsonObject.getString("alipay_trade_refund_response");
            JSONObject jsonObject1 = JSON.parseObject(alipay_trade_refund_response);
            Integer code =Integer.parseInt(jsonObject1.getString("code"));
            //Y
            String fund_change = jsonObject1.getString("fund_change");
            if (Objects.equals(code,10000)&&Objects.equals(fund_change,"Y")){
                return "退款成功";
            }else {
                throw new RuntimeException("退款失败");
            }
        }catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @Override
    @Transactional
    public String del(Integer id) {
        Returngoods returngoods = new Returngoods();
        returngoods.setId(id);
        returngoods.setDeflag(1);
        if (this.updateById(returngoods)){
            return "成功";
        }else {
            throw new RuntimeException("失败");
        }
    }
}
